﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;

namespace EIA.SLClient.Utility.Behaviors
{
    public class PopupCloseOnClickOutsideBehavior : Behavior<System.Windows.Controls.Primitives.Popup>
    {
        Canvas Overlay = null;
        UIElement PopupContent = null;

        public PopupCloseOnClickOutsideBehavior()
        {
            Overlay = new Canvas();
            Overlay.Background = new SolidColorBrush(Color.FromArgb(0, 255, 255, 255));
            Overlay.MouseLeftButtonDown += (s, e) =>
            {
                if (this.AssociatedObject != null) this.AssociatedObject.IsOpen = false;
            };
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            if (AssociatedObject != null)
            {
                this.AssociatedObject.Opened += PopupOpened;
            }
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();
            if (AssociatedObject != null)
            {
                this.AssociatedObject.Opened -= PopupOpened;
                if (PopupContent != null)
                {
                    Overlay.Children.Remove(PopupContent);
                    this.AssociatedObject.Child = PopupContent;
                    PopupContent = null;
                }
            }
        }

        private void PopupOpened(object sender, EventArgs e)
        {
            if (PopupContent == null)
            {
                PopupContent = this.AssociatedObject.Child;
                this.AssociatedObject.Child = Overlay;
                Overlay.Children.Add(PopupContent);
            }
            if (PopupContent != null) ResizeOvelay(Overlay, PopupContent);
        }
        private void ResizeOvelay(Canvas overLay, UIElement popContent)
        {
            //获取Silverlight的整个可见区域大小
            double pageWidth = Application.Current.Host.Content.ActualWidth;
            double pageHeight = Application.Current.Host.Content.ActualHeight;
            //获取Popup在整个可见区域的位置
            Point popContentPosition = popContent.TransformToVisual(null).Transform(new Point(0, 0));
            //将Overlay调整至与可见区域相同大小
            overLay.Width = pageWidth;
            overLay.Height = pageHeight;
            //移动Canvas到可见区域左上角以填充整个区域
            overLay.RenderTransform = new TranslateTransform() { X = -popContentPosition.X, Y = -popContentPosition.Y };
            //Popup的内容会跟着Canvas移动到左上角，因此平移到原来的位置
            popContent.RenderTransform = new TranslateTransform() { X = popContentPosition.X, Y = popContentPosition.Y };
        }
    }
}
